package com.ygxsk.carhome.ui.home;

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.task.DownloadTask;
import com.arialyy.aria.util.ALog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.PopTip;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tencent.mmkv.MMKV;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.ygxsk.carhome.CarApplication;
import com.ygxsk.carhome.ICallbackResult;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.event.EventBusQRCode;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.Delivery;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.GainDataCallBackListener;
import com.ygxsk.carhome.listener.MianTaskManager;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.listener.SequenceListener;
import com.ygxsk.carhome.listener.XXPermissionsDialogDimss;
import com.ygxsk.carhome.permission.PermissionSetting;
import com.ygxsk.carhome.permission.RuntimeRationale;
import com.ygxsk.carhome.response.CustomerShop;
import com.ygxsk.carhome.response.EvaluateWadeDataInfo;
import com.ygxsk.carhome.response.HomeMainAllContent;
import com.ygxsk.carhome.response.HomeMainItemBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxBusEventInfo;
import com.ygxsk.carhome.rxbus.RxBusShopInfo;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.sys.Session;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.HomeMainItemAdapter;
import com.ygxsk.carhome.ui.archive.ArchivesMainActivity;
import com.ygxsk.carhome.ui.auth.AuthManageListActivity;
import com.ygxsk.carhome.ui.care.CardReviewedTabActivity;
import com.ygxsk.carhome.ui.complain.ComplaintHandlerTabActivity;
import com.ygxsk.carhome.ui.consign.ConsignMainTabActivity;
import com.ygxsk.carhome.ui.evaluate.CarEvaluateMainActivity;
import com.ygxsk.carhome.ui.insurance.CarInsuranceTabActivity;
import com.ygxsk.carhome.ui.leads.LeadMainListActivity;
import com.ygxsk.carhome.ui.livefee.FeeOtherActivity;
import com.ygxsk.carhome.ui.message.MessageListActivity;
import com.ygxsk.carhome.ui.paintbook.PaintBookingMainActivity;
import com.ygxsk.carhome.ui.paintbook.QrCodePaintBookBean;
import com.ygxsk.carhome.ui.repair.RepairManageActivity;
import com.ygxsk.carhome.ui.rice.RiceTickMainTabActivity;
import com.ygxsk.carhome.ui.signature.SignatureActivity;
import com.ygxsk.carhome.ui.smartgoout.SmartGoOutActivity;
import com.ygxsk.carhome.ui.usercenter.SettingActivity;
import com.ygxsk.carhome.ui.usercenter.WebViewNormalActivity;
import com.ygxsk.carhome.ui.zxing.MyBGAQRCodeActivity;
import com.ygxsk.carhome.utils.CommTools;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.RC4Utils;
import com.ygxsk.carhome.views.ClearEditText;
import com.ygxsk.carhome.views.spinner.NiceSpinnersk;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-08-03  11:24
 * @Description:首页
 */
public class HomeMainFragmentActivity extends ErrorActivity implements XXPermissionsDialogDimss {
    @BindView(R.id.refreshlayoutinhomemain)
    SmartRefreshLayout refreshLayoutInHomeMain;

    @BindView(R.id.recyclerviewinhomemain)
    RecyclerView recyclerViewInHomeMain;

    //该页面适配填充数据值
    private ArrayList<HomeMainItemBean> mDataResources = new ArrayList<>();
    //店铺列表的信息，是个列表，涉及到切换店铺
    private ArrayList<CustomerShop> customerShopArrayList = new ArrayList<>();
    //该主页列表适配器；
    private HomeMainItemAdapter homeMainItemAdapter;

    private BasePopupView basePopupViewStationType;

    private MaterialDialog materialDialogCustomView;

    private boolean isExit = false;

    private final Handler extiHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            isExit = false;
        }
    };

    //-----------------------------------------------------------
    //仅仅是提示更新的弹窗；
    private MaterialDialog materialDialogHasUpdateData;
    //下载进度的弹窗；
    private MaterialDialog materialDialogDownLoadProgress;

    //该下载apk任务的任务id值内容；
    private long taskDownLoadApkId;
    //-----------------------------------------------------------

    /**
     * 下载服务传递过来的进度
     */
    private ICallbackResult callbackResult = new ICallbackResult() {

        @Override
        public void OnBackResult(final int currentResult) {

            if (currentResult != ConstantApi.APK_DOWNLOADFAIL_FLAG) {

                if (materialDialogDownLoadProgress != null) {

                    try {
                        //materialDialogDownLoadProgress.incrementProgress(1);//每次增加量1
                        materialDialogDownLoadProgress.setProgress(currentResult);//设置进度

                    } catch (Exception e) {
//                        if (!ObjectUtils.isEmpty(e)) {
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "更新-设置页-materialDialogProgress-进度-有异常->" + e.getMessage());
//                        }
                        e.printStackTrace();
                    }

                    materialDialogDownLoadProgress.setOnShowListener(new DialogInterface.OnShowListener() {//更新进度
                        @Override
                        public void onShow(DialogInterface dialoginterface) {
                            //更新进度内容
                            final MaterialDialog curdialog = (MaterialDialog) dialoginterface;

                            if (curdialog.getCurrentProgress() != curdialog.getMaxProgress()) {

                                if (!HomeMainFragmentActivity.this.isFinishing()) {//如果界面没有被杀死

                                    if (curdialog.isCancelled()) {
                                        return;
                                    }

                                }

                            }
                        }
                    });

                } else {
                    //-----------------------------------------------------------------
                    //弹窗没有弹出，那么也是无法下载的，需要杀掉服务;

                    //-----------------------------------------------------------------
                }

            } else {

                try {

                    //do
//                    LogUtils.d("itchen--即将执行-APK_DOWNLOADFAIL_FLAG--解除服务断开，关闭弹窗，杀死服务的工作");

                    if (materialDialogDownLoadProgress != null) {
                        CommUtils.checkMaterialDialog(materialDialogDownLoadProgress);
                    }

                } catch (Exception e) {
                    //catch
//                    if (!ObjectUtils.isEmpty(e)) {
//                        LogUtils.d(ConstantApi.LOGCAT_NOMAL + "下载失败的报错日志=>" + e.getLocalizedMessage());
//                    }
                    e.printStackTrace();

                } finally {
//                    LogUtils.d(ConstantApi.LOGCAT_NOMAL + "必然执行了=>materialDialogProgress再检查关闭一次");
                    if (materialDialogDownLoadProgress != null) {
                        CommUtils.checkMaterialDialog(materialDialogDownLoadProgress);
                    }
                }

            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        if (mDataResources == null) {
            mDataResources = new ArrayList<>();
        }

        if (customerShopArrayList == null) {
            customerShopArrayList = new ArrayList<>();
        }

        initloading();

        initViews();

        gainDatas();

        //注册一个下载器
        Aria.download(this).register();

        //几秒之后检查版本更新；
//        mCompositeDisposable.add(Observable.timer(ConstantApi.TIME_DELAY3000, TimeUnit.MILLISECONDS)
//                .subscribeOn(AndroidSchedulers.mainThread())//
//                .observeOn(AndroidSchedulers.mainThread())//
//                .compose(HomeMainFragmentActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
//                .subscribe(new Consumer<Long>() {
//                    @Override
//                    public void accept(Long aLong) throws Exception {
//                        methodUpdateVersion();
//                    }
//                }));

        //2022年8月8日 因为有隐私政策的弹窗可能会和更新弹窗冲突，需要有限加载新的隐私政策；
        methodUpdateVersion();


        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }


    }

    @Override
    protected void onStart() {
        super.onStart();

        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "onStart---onStart--onStart--onStart");

        mCompositeDisposable.add(Observable.timer(ConstantApi.DELAY_GETCONFIG_IN_HOMEMAINACTIVITY, TimeUnit.MILLISECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                //.compose(HomeFragment.this.bindUntilEvent(FragmentEvent.DESTROY))//
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {

                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "P_TOKEN=>" + MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN));
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "PUBLIC_URL_PREFIX=>" + MMKV.defaultMMKV().decodeString(ConstantSign.PUBLIC_URL_PREFIX));
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "APP_UPDATE_ANDROID_DOWNLOAD_URL=>" + MMKV.defaultMMKV().decodeString(ConstantSign.APP_UPDATE_ANDROID_DOWNLOAD_URL));

                        if (TextUtils.isEmpty(MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN))
                                || TextUtils.isEmpty(MMKV.defaultMMKV().decodeString(ConstantSign.PUBLIC_URL_PREFIX))
                                || TextUtils.isEmpty(MMKV.defaultMMKV().decodeString(ConstantSign.APP_UPDATE_ANDROID_DOWNLOAD_URL))) {

                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "需要再次加强--getSystemConfig");

                            CommUtils.getSystemConfig(HomeMainFragmentActivity.this, mSession, new ApiRequestSubListener() {
                                /**
                                 * 是服务器返回来的约定好的编码的 json 转换时候的异常,在 JsonConverMethod 之中传递。
                                 */
                                @Override
                                public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                                    super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                                }
                            });

                        }
                    }
                }));

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_home_main_fragment;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                .keyboardEnable(false)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//        //这个是没有头部的；
//        toolbarHelper.setTitle(getString(R.string.leadscustomer));
//        toolbarHelper.setLayoutClose(false, "", null);
//        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                //搜索客户信息，优先关闭软键盘
//                KeyboardUtils.hideSoftInput(mActivityInstance);
//                methodBack();
//
//            }
//        });
//
//        //添加潜在客户的按钮
//        toolbarHelper.setLayoutRight(true, 1, "保存", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //快速双加的限制，
//                // TODO: 2023-07-11 16:18 提交潜在客户的信息
//                // TODO: 2023-07-11 14:24 跳转到提交潜在客户页面：
////                Bundle extra_bundle = new Bundle();
////                ActivityUtils.startActivity(extra_bundle, LeadAddSubmitActivity.class);
//
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        //初始化数据；

        //填充适配器
        recyclerViewInHomeMain.setLayoutManager(new GridLayoutManager(this, 2));
        homeMainItemAdapter = new HomeMainItemAdapter(R.layout.homemainadapter, mDataResources);
        recyclerViewInHomeMain.setAdapter(homeMainItemAdapter);

        homeMainItemAdapter.removeAllHeaderView();
        homeMainItemAdapter.removeAllFooterView();

        homeMainItemAdapter.addHeaderView(getHeaderView(recyclerViewInHomeMain));
        homeMainItemAdapter.addFooterView(getFooterView(recyclerViewInHomeMain));

        homeMainItemAdapter.notifyDataSetChanged();

        //单独的此模块点击
        homeMainItemAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                HomeMainItemBean homeMainItemBean = (HomeMainItemBean) adapter.getItem(position);

                if (homeMainItemBean != null) {

                    int purviewCode = homeMainItemBean.getPurviewCode();
                    String url_load = homeMainItemBean.getUrl();

                    switch (purviewCode) {

                        case ConstantApi.CLICK_201: {//潜客客户

                            //潜在客户列表
                            Bundle extra_bundle = new Bundle();
                            ActivityUtils.startActivity(extra_bundle, LeadMainListActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_202: {//投诉管理
                            Bundle extra_bundle = new Bundle();
                            ActivityUtils.startActivity(extra_bundle, ComplaintHandlerTabActivity.class);
                            break;
                        }

                        case ConstantApi.CLICK_203: {//维保管理：维修、保养

                            Bundle extra_bundle = new Bundle();
                            ActivityUtils.startActivity(extra_bundle, RepairManageActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_204: {//订单管理--对接H5

                            //ToastUtils.showShort(("功能未开通"));
                            Bundle extra_bundle = new Bundle();
                            //携带一个标志：
                            //https://echelianhtml.ygxpt.com/order/list?shopInfoId=1495&token=ad6b2ef578f77400772cbf3fef70bbaf

                            extra_bundle.putInt(ExtraKey.EXTRA_WEBVIEW_FLAG, ExtraValue.INDEXT_PATH_ORDER_LIST);
                            //tring extra_webview_loadurl = bundle.getString(ExtraKey.EXTRA_WEBVIEW_LOADURL);
                            extra_bundle.putString(ExtraKey.EXTRA_WEBVIEW_LOADURL, url_load);
                            extra_bundle.putString(ExtraKey.EXTRA_WEBVIEW_TITLENAME, homeMainItemBean.getPurviewName());//标题
                            //titleName = bundle.getString(ExtraKey.EXTRA_WEBVIEW_TITLENAME, "");
                            ActivityUtils.startActivity(extra_bundle, WebViewNormalActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_205: {//车辆评估模块

                            Bundle extra_bundle = new Bundle();
                            ActivityUtils.startActivity(extra_bundle, CarEvaluateMainActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_206: {//客户关怀

                            Bundle extra_bundle = new Bundle();

//                            ActivityUtils.startActivity(extra_bundle, CardMainActivity.class);
                            //2024年1月15日08:51:11 这里是直接跳转到优惠券历史记录页面
//                            ActivityUtils.startActivity(extra_bundle, CardSumHistoryActivity.class);

                            extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY);
//                            ActivityUtils.startActivity(extra_bundle, CardMainTabActivity.class);

                            ActivityUtils.startActivity(extra_bundle, CardReviewedTabActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_207: {//会员管理

                            //ToastUtils.showShort(("功能未开通"));
                            Bundle extra_bundle = new Bundle();
                            //携带一个标志：
                            //https://echelianhtml.ygxpt.com/order/list?shopInfoId=1495&token=ad6b2ef578f77400772cbf3fef70bbaf

                            extra_bundle.putInt(ExtraKey.EXTRA_WEBVIEW_FLAG, ExtraValue.INDEXT_PATH_MEMBER_MANAGE);
                            //tring extra_webview_loadurl = bundle.getString(ExtraKey.EXTRA_WEBVIEW_LOADURL);
                            extra_bundle.putString(ExtraKey.EXTRA_WEBVIEW_LOADURL, url_load);
                            extra_bundle.putString(ExtraKey.EXTRA_WEBVIEW_TITLENAME, homeMainItemBean.getPurviewName());

                            //titleName = bundle.getString(ExtraKey.EXTRA_WEBVIEW_TITLENAME, "");

                            ActivityUtils.startActivity(extra_bundle, WebViewNormalActivity.class);
                            //测试入口代码
//                            ActivityUtils.startActivity(extra_bundle, WebViewDetailActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_208: {//档案管理

                            Bundle extra_bundle = new Bundle();
                            ActivityUtils.startActivity(extra_bundle, ArchivesMainActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_209: {//统计报表

                            ToastUtils.showShort(("功能未开通"));

                            break;
                        }

                        case ConstantApi.CLICK_210: {//车辆认证 二手车认证管理
                            Bundle extra_bundle = new Bundle();
                            ActivityUtils.startActivity(extra_bundle, AuthManageListActivity.class);
                            break;
                        }

                        case ConstantApi.CLICK_211: {//寄售管理-车辆在线寄售

                            Bundle extra_bundle = new Bundle();
                            //ActivityUtils.startActivity(extra_bundle, ConsignMainActivity.class);
                            ActivityUtils.startActivity(extra_bundle, ConsignMainTabActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_212: {//餐券发放

                            Bundle extra_bundle = new Bundle();

//                            ActivityUtils.startActivity(extra_bundle, RiceTicketOutActivity.class);
                            extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY);

                            ActivityUtils.startActivity(extra_bundle, RiceTickMainTabActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_213: {//智能出门

                            Bundle extra_bundle = new Bundle();
                            ActivityUtils.startActivity(extra_bundle, SmartGoOutActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_214: {//车辆保险

                            Bundle extra_bundle = new Bundle();
                            ActivityUtils.startActivity(extra_bundle, CarInsuranceTabActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_215: {//车辆喷涂

                            Bundle extra_bundle = new Bundle();
                            ActivityUtils.startActivity(extra_bundle, PaintBookingMainActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_216: {//合同签约-法大大-电子签章 模块

                            Bundle extra_bundle = new Bundle();
                            ActivityUtils.startActivity(extra_bundle, SignatureActivity.class);

                            break;
                        }

                        case ConstantApi.CLICK_217: {//水费 电费 物业缴费 租赁费

                            Bundle extra_bundle = new Bundle();
//                            ActivityUtils.startActivity(extra_bundle, LiveTabMainActivity.class);
                            ActivityUtils.startActivity(extra_bundle, FeeOtherActivity.class);

                            break;
                        }

                        default:
                            break;
                    }

                }

            }
        });


        //对于下拉刷新的 操作
        refreshLayoutInHomeMain.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        if (homeMainItemAdapter != null) {
                            homeMainItemAdapter.notifyDataSetChanged();
                        }

                        //重新获取店铺信息，然后直接刷新首页的内容
                        gainShopInfoDatas(null);

                        refreshLayout.finishRefresh();
                    }
                });

            }
        });


//        boolean iscanable = NotificationUtils.isNotificationListenerEnabled(HomeMainFragmentActivity.this);
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "通知的状态是否开启-->" + iscanable);
//
//        if (NotificationUtils.isNotificationListenerEnabled(getApplicationContext())) {
//            // 应用已被授权监听通知
//            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "通知的状态是否开启-->已经放开");
//        } else {
//            // 启动系统设置界面，让用户手动开启通知监听服务
//            NotificationUtils.requestNotificationListenerPermission(getApplicationContext());
//        }


    }

    private View getFooterView(RecyclerView _recyclerView) {

        View homeFooter;
        if ((_recyclerView != null) && (_recyclerView.getParent() != null)) {
            //LogUtils.d("itchenqi--->recyclerViewHomeMain.getParent() 不是空");
            homeFooter = LayoutInflater.from(HomeMainFragmentActivity.this).inflate(//
                    R.layout.homefooter, //
                    (ViewGroup) _recyclerView.getParent(),//
                    false);//
        } else {
            //LogUtils.d("itchenqi--->recyclerViewHomeMain.getParent() 空");
            homeFooter = LayoutInflater.from(HomeMainFragmentActivity.this).inflate(R.layout.homefooter, null);
        }

        //retain

        return homeFooter;
    }

    private View getHeaderView(RecyclerView _recyclerView) {

        View homeMainHeader;
//        View headView = LayoutInflater.from(mActivity).inflate(R.layout.item_banner, (ViewGroup) mRv.getParent(), false);

        if ((_recyclerView != null) && (_recyclerView.getParent() != null)) {
            //LogUtils.d("itchenqi--->recyclerViewHomeMain.getParent() 不是空");
            homeMainHeader = LayoutInflater.from(HomeMainFragmentActivity.this).inflate(//
                    R.layout.headerhome, //
                    (ViewGroup) _recyclerView.getParent(),//
                    false);//
        } else {
            //LogUtils.d("itchenqi--->recyclerViewHomeMain.getParent() 空");
            homeMainHeader = LayoutInflater.from(HomeMainFragmentActivity.this).inflate(R.layout.headerhome, null);
        }

        //findviews
        //跳转到设置页面
        LinearLayout linearLayoutSetting = (LinearLayout) homeMainHeader.findViewById(R.id.linearlayoutnametwo);
        //姓名右侧编辑图片
        ImageView imageEditRight = (ImageView) homeMainHeader.findViewById(R.id.imageeditright);
        //消息列表的适配器
        ImageView imageViewMessage = (ImageView) homeMainHeader.findViewById(R.id.imageviewmessage);
        //扫一扫的图标内容
        ImageView imageViewQrCode = (ImageView) homeMainHeader.findViewById(R.id.imageviewqrcode);

        //用户的头像信息
        CircleImageView imageViewHead = (CircleImageView) homeMainHeader.findViewById(R.id.imageviewhead);
        //用户的名称信息
        TextView textUserName = (TextView) homeMainHeader.findViewById(R.id.textusername);
        //用户手机号信息
//        TextView textUserPhone = (TextView) homeMainHeader.findViewById(R.id.textuserphone);
        //岗位信息
        TextView textUserWorkJob = (TextView) homeMainHeader.findViewById(R.id.textuserworkjob);
        //点击切换店铺的信息
        //TextView textSwitchPlace = (TextView) homeMainHeader.findViewById(R.id.textswitchplace);
        NiceSpinnersk nice_spinner_switch_place = (NiceSpinnersk) homeMainHeader.findViewById(R.id.nice_spinner_switch_place);
        nice_spinner_switch_place.setText(StringUtils.getString(R.string.please_choose_store));
        nice_spinner_switch_place.setTextColor(ColorUtils.getColor(R.color.white));

        //用户头像信息
        Delivery.getInstance().post(new Runnable() {
            @Override
            public void run() {

                if (textUserName != null) {
                    textUserName.setText(MMKV.defaultMMKV().decodeString(ConstantSign.P_TRUENAME));
                }
//                if (textUserPhone != null) {
//                    textUserPhone.setText(MMKV.defaultMMKV().decodeString(ConstantSign.P_USERPHONE));
//                }
                if (textUserWorkJob != null) {
                    textUserWorkJob.setText(MMKV.defaultMMKV().decodeString(ConstantSign.P_WORKJOB));
                }

                //!!！特别注意，这是店铺的名字
                if (nice_spinner_switch_place != null) {
                    //2024-2-27 10:10:17 发现bug:退出登录账号需要清空信息，不然下一个用户店铺信息获取为空，结果存入的是上一个账号的店铺。
                    //LogUtils.d(ConstantSign.LOGCAT_NOMAL + "存储的店铺名称是->" + MMKV.defaultMMKV().decodeString(ConstantSign.P_SHOPINFONAME));
                    String shopName = MMKV.defaultMMKV().decodeString(ConstantSign.P_SHOPINFONAME);
                    if (!TextUtils.isEmpty(shopName)) {
                        nice_spinner_switch_place.setText(shopName);
                    } else {
                        nice_spinner_switch_place.setText(StringUtils.getString(R.string.please_choose_store));
//                        nice_spinner_switch_place.setTextColor(ColorUtils.getColor(R.color.white));
                    }
                }

                //处理头像信息
                method_avatar(imageViewHead, MMKV.defaultMMKV().decodeString(ConstantSign.P_PHOTOURL));

            }
        });


        //直接在这里注册是否可以？
        mCompositeDisposable.add(RxBus.getInstance()//
                .toObserverable(RxBusEventInfo.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxBusEventInfo>() {//
                    @Override
                    public void accept(RxBusEventInfo eventInfo) throws Exception {

                        int actionFlag = eventInfo.getActionFlag();
                        String messagecontent = eventInfo.getMsg();

                        if (actionFlag == ConstantApi.RXBUS_MODIFY_AVATAR) {//更改了头像
                            //这里没有进行
                            //LogUtils.d("itchen--MineFragment-mCompositeDisposable---内部准备执行method_touxiang");
                            if (!HomeMainFragmentActivity.this.isFinishing()) {
                                method_avatar(imageViewHead, messagecontent);//messagecontent 内容就是头像地址信息，
                            }
                        }
                    }
                }));

        //这是通过变动【勾选哪个店铺】然后变动店铺id和店铺名称；
        mCompositeDisposable.add(RxBus.getInstance()//
                .toObserverable(RxBusShopInfo.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxBusShopInfo>() {//
                    @Override
                    public void accept(RxBusShopInfo rxBusShopInfo) throws Exception {

                        int actionFlag = rxBusShopInfo.getActionFlag();
                        CustomerShop customerShop = rxBusShopInfo.getCustomerShop();

                        if (actionFlag == ExtraValue.MODIFY_HOMEMAIN_SHOPINFO_STATION_SELECT) {//更改了店铺信息和重新存储id等

                            LogUtils.d("itchen--getHeaderView--mCompositeDisposable---内部准备 切换店铺-->" + customerShop);

                            if (nice_spinner_switch_place != null) {
                                nice_spinner_switch_place.setText(customerShop.getShopName());
                            }

                            //切换店铺的id
                            mSession.setShopInfoId(customerShop.getShopInfoId());
                            mSession.setShopInfoName(customerShop.getShopName());

                        }
                    }
                }));

        //跳转到消息列表
        if (imageViewMessage != null) {
            imageViewMessage.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {
                    ActivityUtils.startActivity(MessageListActivity.class);
                }
            });
        }

        //扫一扫的逻辑，是多个逻辑的内容。
        imageViewQrCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //提前告知需要的权限内容
                //判断版本
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                    if (!AndPermission.hasPermissions(mActivityInstance, Permission.CAMERA)//
                            || !AndPermission.hasPermissions(mActivityInstance, Permission.WRITE_EXTERNAL_STORAGE)//
                            || !AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE)) {//


                        CommUtils.checkMaterialDialog(materialDialog);

                        materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_CAMERA_STORAGE, new AuthorityCallbackListener() {
                            @Override
                            public void doSomeThing() {

                                CommUtils.checkMaterialDialog(materialDialog);

                                //添加访问权限内容
                                AndPermission.with(HomeMainFragmentActivity.this)
                                        .runtime()//
                                        .permission(Permission.CAMERA,
                                                Permission.READ_EXTERNAL_STORAGE, //
                                                Permission.WRITE_EXTERNAL_STORAGE)//
                                        .rationale(new RuntimeRationale())//
                                        .onGranted(new com.yanzhenjie.permission.Action<List<String>>() {
                                            @Override
                                            public void onAction(List<String> permissions) {

                                                methodToQRCode();

                                            }
                                        }).onDenied(new com.yanzhenjie.permission.Action<List<String>>() {
                                            @Override
                                            public void onAction(List<String> permissions) {

                                                ToastUtils.showShort(ConstantSign.NEEDPERMISS_PHONE);
                                                PermissionSetting permissionSetting = new PermissionSetting(mActivityInstance);

                                                if (AndPermission.hasAlwaysDeniedPermission(HomeMainFragmentActivity.this, permissions)) {
                                                    permissionSetting.showSetting(ConstantApi.PERMISSION_NORMAL, HomeMainFragmentActivity.this, permissions);
                                                }

                                            }
                                        }).start();

                            }
                        });

                    } else {

                        methodToQRCode();

                    }

                } else {

                    //高于Android13版本。
//                        public static final String READ_MEDIA_AUDIO = "android.permission.READ_MEDIA_AUDIO";
//                        public static final String READ_MEDIA_IMAGES = "android.permission.READ_MEDIA_IMAGES";
//                        public static final String READ_MEDIA_VIDEO = "android.permission.READ_MEDIA_VIDEO";

                    if (!XXPermissions.isGranted(HomeMainFragmentActivity.this, com.hjq.permissions.Permission.CAMERA)
                            || !XXPermissions.isGranted(HomeMainFragmentActivity.this, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

                        CommUtils.checkMaterialDialog(materialDialog);

                        materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_CAMERA_STORAGE, new AuthorityCallbackListener() {

                            @Override
                            public void doSomeThing() {

                                CommUtils.checkMaterialDialog(materialDialog);

                                XXPermissions.with(HomeMainFragmentActivity.this)
                                        // 适配分区存储应该这样写
                                        //.permission(Permission.Group.STORAGE)
                                        // 不适配分区存储应该这样写
                                        .permission(com.hjq.permissions.Permission.CAMERA)//
                                        .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
//                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_VIDEO)//
//                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_AUDIO)//
                                        //).permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
//                                                        .interceptor(new PermissionInterceptor())
                                        .request(new OnPermissionCallback() {

                                            @Override
                                            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                                if (!allGranted) {
                                                    // TODO: 2024/1/23 18:50 权限这里要不要给提示？权限没通过

                                                    return;
                                                }

                                                Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                        PermissionNameConvert.getPermissionString(HomeMainFragmentActivity.this, permissions)));

                                                methodToQRCode();

                                            }
                                        });

                            }

                        });

                    } else {
                        methodToQRCode();
                    }
                }
            }
        });

        if (nice_spinner_switch_place != null) {

            nice_spinner_switch_place.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {

                    ShopSwitchBottomPopu shopSwitchBottomPopu = new ShopSwitchBottomPopu(HomeMainFragmentActivity.this,//
                            ExtraValue.VALUE_JUMP_FORM_HOMEMAIN_ACTIVITY,//
                            customerShopArrayList);

                    shopSwitchBottomPopu.setTitleName(getResources().getString(R.string.dialog_des_store));

                    //添加点击事件：这里是展示一个弹窗；
                    // TODO: 2023-08-05 17:32 添加店铺的切换
                    if (customerShopArrayList != null && !customerShopArrayList.isEmpty()) {
                        //直接弹窗：
                        basePopupViewStationType = new XPopup.Builder(HomeMainFragmentActivity.this)
                                .hasShadowBg(true)
                                //.moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                                .isViewMode(true)
                                .isThreeDrag(false) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                                .moveUpToKeyboard(false)
                                .asCustom(shopSwitchBottomPopu)//
                                .show();

                    } else {

                        //那么这次需要重新获取接口再次弹窗调用
                        //直接重新获取接口，取在线值；
                        gainShopInfoDatas(new GainDataCallBackListener() {
                            @Override
                            public void doSomeThing() {

                                //直接弹窗：
                                basePopupViewStationType = new XPopup.Builder(HomeMainFragmentActivity.this)
                                        .hasShadowBg(true)
                                        //.moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                                        .isViewMode(true)
                                        //.autoDismiss(false)
                                        //.isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                                        .isThreeDrag(false) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                                        //.dismissOnTouchOutside(true)
                                        //.notDismissWhenTouchInView()
                                        .moveUpToKeyboard(false)
                                        .asCustom(shopSwitchBottomPopu)//
                                        .show();

                            }
                        });

                    }
                }
            });
        }

        if (linearLayoutSetting != null) {
            linearLayoutSetting.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityUtils.startActivity(SettingActivity.class);//设置界面
                }
            });
        }

        //姓名点击
        if (textUserName != null) {
            textUserName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityUtils.startActivity(SettingActivity.class);
                }
            });
        }

        //姓名右侧图片点击
        if (imageEditRight != null) {
            imageEditRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityUtils.startActivity(SettingActivity.class);
                }
            });
        }

        //岗位
        if (textUserWorkJob != null) {
            textUserWorkJob.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityUtils.startActivity(SettingActivity.class);
                }
            });
        }

        //==================================================================================
//        //测试一个弹窗为的是
//        ImageView imageviewhomtop = (ImageView) homeMainHeader.findViewById(R.id.imageviewhomtop);
//        imageviewhomtop.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//
//                BottomMenu.build()
//                        .setBottomDialogMaxHeight(0.6f)
//                        .setMenuList(new String[]{
//                                "智能出门",////
//                                "智能出门",////
//                                "智能出门",////
//                                "智能出门",////
//                                "智能出门",////
//                                "智能出门",////
//                                "智能出门",////
//                                "智能出门",////
//                                "智能出门",////
//                                "智能出门",////
//                        })
//                        .setOnMenuItemClickListener(new OnMenuItemClickListener<BottomMenu>() {
//                            @Override
//                            public boolean onClick(BottomMenu dialog, CharSequence text, int index) {
//
//                                PopTip.show(text);
//
//                                switch (index) {
//
//                                    case 0: {
//                                        //潜在客户列表
//                                        Bundle extra_bundle = new Bundle();
//                                        // ActivityUtils.startActivity(extra_bundle, LeadMainListActivity.class);
////                                        ActivityUtils.startActivity(extra_bundle, ConsignMainActivity.class);
//                                        ActivityUtils.startActivity(extra_bundle, SmartGoOutActivity.class);
//
//                                        break;
//                                    }
//
//                                    case 1: {
//                                        //潜在客户列表
//                                        Bundle extra_bundle = new Bundle();
//                                        // ActivityUtils.startActivity(extra_bundle, LeadMainListActivity.class);
////                                        ActivityUtils.startActivity(extra_bundle, ConsignMainActivity.class);
//                                        ActivityUtils.startActivity(extra_bundle, SmartGoOutActivity.class);
//
//                                        break;
//                                    }
//
//                                    default:
//                                        break;
//                                }
//                                return false;
//                            }
//                        })
//                        .show();
//
//                return true;
//            }
//        });

        return homeMainHeader;
    }

    @Override
    protected void gainDatas() {

        //首次是空值的，
        gainShopInfoDatas(null);

    }

    private void gainShopInfoDatas(GainDataCallBackListener _gainDataCallBackListener) {

        HashMap<String, Object> map = new HashMap<>();
        //map.put(Parameterkey.usertoken, MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN));
        map.put("", "");

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETCUSTOMERSHOP_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getShopInfoByCustomer_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getShopInfoByCustomer(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(HomeMainFragmentActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<CustomerShop>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //如果发现这个接口发生
                        //{"code":"10005","data":"","message":"token不能为空!"}
                        CommTools.errorTokenOrEqument(mActivityInstance, serverCode, serverMessage, mSession, new SequenceListener() {
                            @Override
                            public void doSomeThing() {

                                //2024-2-27 10:05:17发现该接口无数据，提示给用户
                                if (!TextUtils.isEmpty(serverMessage)) {
                                    ToastUtils.showShort(serverMessage);
                                } else {
                                    ToastUtils.showShort(getResources().getString(R.string.action_abnormal_toast));
                                }

                            }
                        });


                    }
                })).subscribe(new Consumer<ArrayList<CustomerShop>>() {
                    @Override
                    public void accept(ArrayList<CustomerShop> customerShops) throws Throwable {

                        //店铺的id，这里存储起来，
                        if (customerShopArrayList != null && !customerShopArrayList.isEmpty()) {
                            customerShopArrayList.clear();
                        }

                        if (customerShops != null && !customerShops.isEmpty()) {
                            if (customerShopArrayList != null) {
                                customerShopArrayList.addAll(customerShops);
                            }
                        }

                        //添加默认的第一个值内容
                        if (customerShopArrayList != null && !customerShopArrayList.isEmpty()) {

                            CustomerShop customerShopFirstOne = customerShopArrayList.get(0);

//                            String shopInfoName = customerShop.getShopName();
//                            mSession.setShopInfoName(shopInfoName);

                            //直接调用【首页】的接口；
                            gainDataHomePage(customerShopFirstOne.getShopInfoId());

                            RxBusShopInfo rxBusShopInfo = new RxBusShopInfo();
                            rxBusShopInfo.setActionFlag(ExtraValue.MODIFY_HOMEMAIN_SHOPINFO_STATION_SELECT);
                            rxBusShopInfo.setCustomerShop(customerShopFirstOne);
                            RxBus.getInstance().post(rxBusShopInfo);

                        } else {

                            // TODO: 2023-10-09 17:17 如果是空的，那么要遮盖底部，不然是一个空白；
                            String shopIdError = getString(R.string.shopid_error);
                            PopTip.show(shopIdError).iconWarning();

                        }

                        if (_gainDataCallBackListener != null) {
                            _gainDataCallBackListener.doSomeThing();
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //如果报错属于10000类型的；这里给个提示
                        if (apiException != null) {
                            ToastUtils.showShort(apiException.getDisplayMessage());
                        }

                    }
                });


    }

    //首页的接口对接
    private void gainDataHomePage(String _shopInfoId) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, _shopInfoId);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETAPPHOMEFORMANAGER_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getAppHomeForManager_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);
        addLogUpLoadInfo.setAlertToUser(true);
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getAppHomeForManager(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(HomeMainFragmentActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<HomeMainAllContent>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        // TODO: 2024/2/27 10:36 醒目提示 店铺首页信息直接报错；
                        function_response_20002(serverCode, serverMessage, addLogUpLoadInfo, true);

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        //避开旧数据的遮盖
                        if (homeMainItemAdapter != null) {
                            if (notDataView != null) {
                                homeMainItemAdapter.removeHeaderView(notDataView);
                            }
                        }

                    }
                }).subscribe(new Consumer<HomeMainAllContent>() {
                    @Override
                    public void accept(HomeMainAllContent homeMainAllContent) throws Throwable {

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        if (homeMainAllContent != null) {

                            ArrayList<HomeMainItemBean> appPurviewListArrayList = homeMainAllContent.getAppPurviewList();

                            if (appPurviewListArrayList != null && !appPurviewListArrayList.isEmpty()) {

                                if (mDataResources != null) {
                                    mDataResources.addAll(appPurviewListArrayList);
                                }

                            } else {

                                //bug：2024-2-27 发现用户分配了店铺，但是没有分配首页模块，那么给醒目提示
                                CommUtils.checkDialog(mAlertView);
                                mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getResources().getString(R.string.home_app_module_not), true);
                                mAlertView.show();

                                //---------------------------------------------------------------------------------
                                if (recyclerViewInHomeMain != null) {
                                    recyclerViewInHomeMain.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            homeMainItemAdapter.addHeaderView(getEmptyDataView(getResources().getString(R.string.home_app_module_not)), 1, LinearLayout.VERTICAL);
                                        }
                                    });
                                }
                                //---------------------------------------------------------------------------------

                            }

                        }

                        if (homeMainItemAdapter != null) {
                            homeMainItemAdapter.notifyDataSetChanged();
                        }

                        // TODO: 2023-09-13 21:38 开始调用字典值内容
                        gainDatasCallHistoryBusinessType();

                        //检测用户的通知权限：
                        //如果是首次登录？，不能检测通知权限
                        mCompositeDisposable.add(Observable.timer(ConstantApi.DELAY_SETNOTIFICATION_DIALOG, TimeUnit.MILLISECONDS)
                                .subscribeOn(AndroidSchedulers.mainThread())//
                                .observeOn(AndroidSchedulers.mainThread())//
                                .compose(HomeMainFragmentActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                                .subscribe(new Consumer<Long>() {
                                    @Override
                                    public void accept(Long aLong) throws Exception {

                                        //LogUtils.d(ConstantSign.LOGCAT_NOMAL + "P_TOKEN=>" + MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN));

                                        CommTools.setNotification(HomeMainFragmentActivity.this, HomeMainFragmentActivity.this, HomeMainFragmentActivity.this, false);

                                    }
                                }));
                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        if (apiException != null) {

                            ToastUtils.showShort(apiException.getDisplayMessage());

//                            if (recyclerViewInHomeMain!=null) {
//                                recyclerViewInHomeMain.post(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        homeMainItemAdapter.setEmptyView(getEmptyDataView("apiException.getDisplayMessage()"));
//                                    }
//                                });
//                            }

                        }
                    }
                });


    }


    //获取 拨打电话的类型
    private void gainDatasCallHistoryBusinessType() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.callHistoryBusinessType, Parameterkey.callHistoryBusinessType);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETLISTBYTYPE_CALLPHONE);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getListByType_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getListByType_callPhone(Parameterkey.callHistoryBusinessType)
                .compose(HomeMainFragmentActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<EvaluateWadeDataInfo>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        //这里是不给提示的
                    }
                })).subscribe(new Consumer<ArrayList<EvaluateWadeDataInfo>>() {
                    @Override
                    public void accept(ArrayList<EvaluateWadeDataInfo> evaluateWadeInfos) throws Throwable {

                        //将手动本地填充的清空也行；
//                        if (mDataResources_wade != null && !mDataResources_wade.isEmpty()) {
//                            mDataResources_wade.clear();
//                        }

                        if (evaluateWadeInfos != null && !evaluateWadeInfos.isEmpty()) {

                            // TODO: 2023-09-13 21:43 存储值内容
                            String jsonString = JSON.toJSONString(evaluateWadeInfos);
                            //LogUtils.d(ConstantSign.LOGCAT_NOMAL + "jsonString-->" + jsonString);
                            MMKV.defaultMMKV().encode(ConstantSign.P_MMKV_CALL_PHONE, jsonString);

                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        //
                    }
                });


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            //===================================================================================================
            //===================================================================================================

            if (!isExit) {

                isExit = true;
                ToastUtils.showShort(getResources().getString(R.string.textexit));
                extiHandler.sendEmptyMessageDelayed(0, 2000);

            } else {

                //methodKillClearData();
//                LogUtils.d("itchen----->让应用【人为的，主动的】回到桌面上，不杀死");
                //2021/8/2 0002 at 11:20 添加标识为：下次展开，如果本地有 未提交的数据，那末，弹出 提交弹窗。
//                MMKV.defaultMMKV().encode(ConstantSign.P_IS_JUDGMENT_HAVASOMEDATAINDAOS_MUST_SHOW_DIALOG, true);
//                ActivityUtils.startHomeActivity();

                //该页面的msession;

                if (mSession != null) {

                    //LogUtils.d("itchen---->应用即将 退出");
//                    mSession.deleteObservers();
//                    mSession.close();
                    mSession = null;

                }

                if (ActivityUtils.isActivityAlive(HomeMainFragmentActivity.this)) {
                    ActivityUtils.finishActivity(HomeMainFragmentActivity.this);
                }

                if (MianTaskManager.getInstance(this) != null) {
                    MianTaskManager.getInstance(this).finishAllActivity();
                }

                ActivityUtils.finishAllActivities();
                AppUtils.exitApp();

            }

            return false;
        }

        return super.onKeyDown(keyCode, event);
    }

    //设置版本更新，的弹窗

    private void methodUpdateVersion() {

        mCompositeDisposable.add(Observable.timer(1, TimeUnit.SECONDS)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .compose(HomeMainFragmentActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {

                                /*if (CommUtils.isNotificationEnabled(Utils.getApp())){
                                    LogUtils.d("itchen--->通知设置状态---打开");
                                }else{
                                    LogUtils.d("itchen--->通知设置状态---未打开");
                                }
                                //测试
                                boolean isEnable = NotificationUtils.areNotificationsEnabled();
                                LogUtils.d("itchen-----通知是否可用--->"+isEnable);*/

                        getVersion();

                    }
                }));

    }

    private void getVersion() {

        //如果后台的 【版本数字】 大于 【当前版本】的版本号；
        if (CommUtils.getServiceVersionCode(Session.get(HomeMainFragmentActivity.this)) > AppUtils.getAppVersionCode()) {

            //showDownLoadDialog(mSession.getDownloadurlCurrent());

            final File apkFile = new File(PathUtils.getExternalAppCachePath() + File.separator +//
                    mSession.getDownloadurlCurrent().substring(mSession.getDownloadurlCurrent().lastIndexOf("/") + 1));

            if (FileUtils.isFileExists(apkFile)) {
                if (CommUtils.getUninatllApkInfo(Utils.getApp(), apkFile.getAbsolutePath())) {
                    AppUtils.installApp(apkFile.getAbsolutePath());
                } else {
                    //如果已存在的安装包不完整那么也直接弹窗提示
                    showDownLoadDialog(mSession.getDownloadurlCurrent());
                }
            } else {
                showDownLoadDialog(mSession.getDownloadurlCurrent());
            }

        }

    }

    //版本更新的弹窗：
    private void showDownLoadDialog(final String _downLoadUrlCurrent) {

        //点击边缘不可更改。要不要区分？强制更新、不强制更新。
        CommUtils.checkMaterialDialog(materialDialogHasUpdateData);

        if (ActivityUtils.isActivityAlive(HomeMainFragmentActivity.this)) {

            materialDialogHasUpdateData = new MaterialDialog.Builder(HomeMainFragmentActivity.this)
                    .title(R.string.updateinfotitle)
                    .titleColor(ContextCompat.getColor(Utils.getApp(), R.color.dark))
                    .content(StringUtils.getString(R.string.updateappinfo))
                    .contentColor(ContextCompat.getColor(Utils.getApp(), R.color.dark))
                    .positiveText(R.string.updateformserver)//右侧下载：从服务器下载
                    .positiveColor(ContextCompat.getColor(Utils.getApp(), R.color.red_normal))
                    .negativeText(R.string.updatebuttoncancel)//左侧取消
                    .negativeColor(ContextCompat.getColor(Utils.getApp(), R.color.colormobutton))
                    .neutralText(R.string.updateforlooker)//中性的-从浏览器下载
                    .neutralColor(ContextCompat.getColor(Utils.getApp(), R.color.colormobutton))//中性的
                    .onPositive(new MaterialDialog.SingleButtonCallback() {//从服务器下载；
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {


                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                if (!AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)) {

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {
                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            //2018年06月05日发现这里添加SD卡的存储权限内容
                                            AndPermission.with(HomeMainFragmentActivity.this)//
                                                    .runtime()//
                                                    .permission(Permission.READ_EXTERNAL_STORAGE,//
                                                            Permission.WRITE_EXTERNAL_STORAGE)//
                                                    .rationale(new RuntimeRationale())//
                                                    .onGranted(new com.yanzhenjie.permission.Action<List<String>>() {//
                                                        @Override
                                                        public void onAction(List<String> permissions) {

                                                            method_inside_download(_downLoadUrlCurrent);

                                                        }
                                                    }).onDenied(new com.yanzhenjie.permission.Action<List<String>>() {
                                                        @Override
                                                        public void onAction(List<String> permissions) {
                                                            //弹出失败弹窗
                                                            if (AndPermission.hasAlwaysDeniedPermission(HomeMainFragmentActivity.this, permissions)) {//
                                                                PermissionSetting mSetting = new PermissionSetting(HomeMainFragmentActivity.this);
                                                                mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, HomeMainFragmentActivity.this, permissions);//
                                                            }
                                                        }
                                                    }).start();

                                        }
                                    });

                                } else {
                                    method_inside_download(_downLoadUrlCurrent);
                                }

                            } else {

                                //如果获取android13高版本的
                                //打开文件管理权限
                                if (!XXPermissions.isGranted(mActivityInstance, com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)) {

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {
                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            XXPermissions.with(HomeMainFragmentActivity.this)
                                                    // 适配分区存储应该这样写
                                                    //.permission(Permission.Group.STORAGE)
                                                    // 不适配分区存储应该这样写
                                                    .permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)//
//                                            .interceptor(new PermissionInterceptor())
                                                    .request(new OnPermissionCallback() {

                                                        @Override
                                                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                                            if (!allGranted) {
                                                                // TODO: 2024/1/23 18:50 权限这里要不要给提示？权限没通过

                                                                return;
                                                            }

                                                            Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                                    PermissionNameConvert.getPermissionString(HomeMainFragmentActivity.this, permissions)));

                                                            method_inside_download(_downLoadUrlCurrent);

                                                        }
                                                    });

                                        }
                                    });

                                } else {

                                    method_inside_download(_downLoadUrlCurrent);

                                }

                            }

                        }
                    })
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {

                            //取消的
                            dialog.dismiss();

                        }
                    }).onNeutral(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                            //直接启用浏览器下载
                            CommUtils.method_inside_download(_downLoadUrlCurrent, HomeMainFragmentActivity.this);

                            dialog.dismiss();
                        }
                    }).dismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
//                            mSession.setQuitUpdate(true);
                            dialog.dismiss();
                            //LogUtils.d("itchen触发取消视图的事件dismissListener");
                        }
                    }).canceledOnTouchOutside(false).show();//只有点击取消才能让升级框消失

            //2019/1/27 去掉设置顶部标题
            //materialDialog.getTitleView().setTextSize(13);
            materialDialogHasUpdateData.getTitleView().setTextSize(15);
            materialDialogHasUpdateData.getActionButton(DialogAction.POSITIVE).setTextSize(15);
            //materialDialogUpdate.getActionButton(DialogAction.NEGATIVE).setTextSize(15);

        }
    }


    //直接执行下载
    private void method_inside_download(String _downLoadUrlCurrent) {

        //LogUtils.d("itchen--确定按钮");
//        mSession.setQuitUpdate(true);

        //2019年12月11日 这段代码暂时不用。
//        Intent updateIntent = new Intent();
//        updateIntent.setClass(SettingActivity.this, UpdateService.class);
//        updateIntent.putExtra(Parameterkey.nameapk, AppUtils.getAppName());
//        updateIntent.putExtra(Parameterkey.urlapk, _downLoadUrlCurrent);
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService(updateIntent);
//        } else {
//            startService(updateIntent);
//        }
//
//        //将来如果这一块有问题直接屏蔽即可
//        showProgressDialog();


        //使用浏览器下载 ：
        //弹窗其实是否打开链接
//        final Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_VIEW);
//        intent.setData(Uri.parse(_downLoadUrlCurrent));
//        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
//        // 官方解释 : Name of the component implementing an activity that can display the intent
//        if (intent.resolveActivity(SettingActivity.this.getPackageManager()) != null) {
//            //final ComponentName componentName = intent.resolveActivity(getPackageManager());
//            // 打印Log   ComponentName 到底是什么
//            //Log.e(TAG, "componentName = " + componentName.getClassName());
//            mActivityInstance.startActivity(Intent.createChooser(intent, getString(R.string.plesechooseintent)));
//
//        } else {
//            ToastUtils.showShort(R.string.nochooseappdownload);
//        }

        //PathUtils.getExternalAppCachePath() + File.separator + ConstantSign.DOWNAPP + File.separator,//
        //                (down_url.substring(down_url.lastIndexOf("/") + 1)

        //打开下载进度的弹窗内容；
        //将来如果这一块有问题直接屏蔽即可
        showProgressDialog();

        //String filePath = PathUtils.getExternalAppCachePath() + File.separator + ConstantSign.DOWNAPP + File.separator+(_downLoadUrlCurrent.substring(_downLoadUrlCurrent.lastIndexOf("/") + 1));
//        String filePath = PathUtils.getExternalAppFilesPath() + File.separator + (_downLoadUrlCurrent.substring(_downLoadUrlCurrent.lastIndexOf("/") + 1));
        //String filePath = PathUtils.getExternalAppCachePath() + File.separator + (_downLoadUrlCurrent.substring(_downLoadUrlCurrent.lastIndexOf("/") + 1));

        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "下载存放路径地址-->" + CarApplication.getInstance().getApkDownLoadPath(_downLoadUrlCurrent));
        //itchen-->下载存放路径地址-->/data/user/0/com.ygxsk.carhome/cache/汽车员工端3.apk

        //使用第三方下载
        taskDownLoadApkId = Aria.download(this)
                .load(_downLoadUrlCurrent)
                .setFilePath(CarApplication.getInstance().getApkDownLoadPath(_downLoadUrlCurrent)) //设置文件保存的完整路径
                .create();   //启动下载

    }

    private void showProgressDialog() {

        //关闭上一个
        CommUtils.checkMaterialDialog(materialDialogHasUpdateData);
        CommUtils.checkMaterialDialog(materialDialogDownLoadProgress);

        if (ActivityUtils.isActivityAlive(HomeMainFragmentActivity.this)) {

            materialDialogDownLoadProgress = new MaterialDialog.Builder(HomeMainFragmentActivity.this)
                    .title(AppUtils.getAppName())
                    .content(R.string.downloadingwait)
                    .contentGravity(GravityEnum.CENTER)
                    .progress(false, 100, true)//itchen自己更改 false水平进度条
                    .positiveText(R.string.backgrounddown)//右侧下载
                    .positiveColor(ContextCompat.getColor(Utils.getApp(), R.color.red_normal))
                    .negativeText(R.string.downloadingcancel)//左侧取消
                    .negativeColor(ContextCompat.getColor(Utils.getApp(), R.color.colormobutton))
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {

                            dialog.dismiss();//取消弹窗，取消下载，取消发送进度内容

                        }
                    })
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {

                            //触发取消下载。
                            //杀死服务和服务内发送下载的方法
                            //binderInterface.callCancel();

                            //调用下载器的 取消
                            if (Aria.download(HomeMainFragmentActivity.this).load(taskDownLoadApkId).isRunning()) {
                                Aria.download(HomeMainFragmentActivity.this).load(taskDownLoadApkId).cancel();
                            }

                        }
                    }).canceledOnTouchOutside(false)//
                    .show();//

            //先创建，然后更新
            //2019/1/27 不修改标题字号,显示为默认的
            materialDialogDownLoadProgress.getTitleView().setTextSize(16);
            //materialDialogProgress.getProgressBar().setAlpha(ContextCompat.getColor(Dutils.getApp(),R.color.colormobutton));
            materialDialogDownLoadProgress.getProgressBar().setAlpha(1);

            materialDialogDownLoadProgress.getActionButton(DialogAction.POSITIVE).setTextSize(15);
            materialDialogDownLoadProgress.getActionButton(DialogAction.NEGATIVE).setTextSize(15);
        }

    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning
    protected void running(DownloadTask task) {

//        if(task.getKey().eques(task.getKey())){
//        ....
//            可以通过url判断是否是指定任务的回调
//        }
        int p = task.getPercent();  //任务进度百分比
//        String speed = task.getConvertSpeed();  //转换单位后的下载速度，单位转换需要在配置文件中打开
//        String speed1 = String.valueOf(task.getSpeed()); //原始byte长度速度
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL+"下载进度是-->"+speed);
        //LogUtils.d(ConstantSign.LOGCAT_NOMAL + "下载进度是-->" + p);

        if (callbackResult != null) {
            callbackResult.OnBackResult(p);
        }

    }

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        //在这里处理任务完成的状态
        //下载完毕
        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "下载完毕；");

        CommUtils.checkMaterialDialog(materialDialogHasUpdateData);
        if (materialDialogHasUpdateData != null) {
            materialDialogHasUpdateData = null;
        }

        CommUtils.checkMaterialDialog(materialDialogDownLoadProgress);
        if (materialDialogDownLoadProgress != null) {
            materialDialogDownLoadProgress = null;
        }

        //String filePath = PathUtils.getExternalAppCachePath() + File.separator + (_downLoadUrlCurrent.substring(_downLoadUrlCurrent.lastIndexOf("/") + 1));
        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "下载完毕后的地址-->" + task.getFilePath());
        // itchen-->下载完毕后的地址-->/data/user/0/com.ygxsk.carhome/cache/汽车员工端3.apk


        //直接启用安装
        if (!TextUtils.isEmpty(task.getFilePath())) {
            if (CommUtils.getUninatllApkInfo(HomeMainFragmentActivity.this, task.getFilePath())) {
                ///data/user/0/com.ygxsk.integrated/cache/2970b8290303428eb08f0805be10db3d.apk
                AppUtils.installApp(task.getFilePath());
            }
        }

    }

    @Download.onTaskCancel
    void taskCancel(DownloadTask task) {

        //LogUtils.d(ConstantSign.LOGCAT_NOMAL+"---->下载取消---");

        //mAdapter.updateState(task.getEntity());
        //判断这个任务在运行的状态中，那么，就直接停止它；
//        if (Aria.download(SettingActivity.this).load(taskDownLoadApkId).isRunning()){
//            Aria.download(SettingActivity.this).load(taskDownLoadApkId).stop();
//        }

        //直接关闭 下载弹窗；
        //立即关闭弹窗的
        CommUtils.checkMaterialDialog(materialDialogHasUpdateData);
        CommUtils.checkMaterialDialog(materialDialogDownLoadProgress);

        ToastUtils.showLong(R.string.downlaodappcancel);

    }

    /**
     * @param e 异常信息
     */
    @Download.onTaskFail
    void taskFail(DownloadTask task, Exception e) {

        //立即关闭弹窗的
        CommUtils.checkMaterialDialog(materialDialogHasUpdateData);
        CommUtils.checkMaterialDialog(materialDialogDownLoadProgress);

        //ALog.d(TAG, ALog.getExceptionString(e));
        //下载任务失败
        //下载失败
        if (!TextUtils.isEmpty(ALog.getExceptionString(e))) {
            ToastUtils.showShort(ALog.getExceptionString(e));
            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "---->下载报错--->" + ALog.getExceptionString(e));
            // com.arialyy.aria.exception.AriaHTTPException: Aria HTTP Exception:
            //    任务下载失败，errorCode：404, url: http://222.222.17.184:8990/resource/17531108969-1499认证二维码.jpg

            //提示下载失败：
            ToastUtils.showShort(ALog.getExceptionString(e));
        }

    }

    View notDataView = null;

    //空数据页面单独的填充
    private View getEmptyDataView(String _errorMessage) {

        //因为外侧有判断，所以内侧不用再次判断
//        if (recyclerViewInHomeMain != null) {

        notDataView = getLayoutInflater().inflate(R.layout.empty_view_my, recyclerViewInHomeMain, false);

        //错误信息内容
        if (notDataView != null) {

            TextView textViewEmptyFill = (TextView) notDataView.findViewById(R.id.textViewEmptyFill);
            textViewEmptyFill.setText(_errorMessage);

            notDataView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //reset刷新数据
                    //触发下拉刷新的逻辑
//                    if (homeMainItemAdapter != null) {
//                        if (notDataView != null) {
//                            homeMainItemAdapter.removeHeaderView(notDataView);
//                        }
//                    }

                    if (refreshLayoutInHomeMain != null) {
                        refreshLayoutInHomeMain.autoRefresh();
                    }

                }
            });

        }
//        }

        return notDataView;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadQRcodeResult(EventBusQRCode eventBusQRCode) {

        if (eventBusQRCode != null) {

            if (eventBusQRCode.getMessage() == ExtraValue.BGAQRCODE_VALUE_FROM_HOME_MAIN) {

                //扫描的二维码是被加密的。
                String qrCodeResult_encrypted = eventBusQRCode.getContent();
//                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "原始扫码内容 qrCodeResult_encrypted：-->" + qrCodeResult_encrypted);

                if (!TextUtils.isEmpty(qrCodeResult_encrypted)) {

                    if (qrCodeResult_encrypted.contains(Parameterkey.QRCODE_HTTP)) {

                        CommUtils.linkJumpDialog(HomeMainFragmentActivity.this, HomeMainFragmentActivity.this, qrCodeResult_encrypted);

                    } else {

                        //这里要对扫码做解密处理
                        try {

                            String qrCodeResult_decrypt = RC4Utils.decry_RC4(qrCodeResult_encrypted, RC4Utils.pub_key);
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "qrCodeResult_decrypt：-->" + qrCodeResult_decrypt);

                            QrCodePaintBookBean qrCodePaintBookBean = JSON.parseObject(qrCodeResult_decrypt, QrCodePaintBookBean.class);

                            if (qrCodePaintBookBean != null) {

                                String param = qrCodePaintBookBean.getParam();
                                //标志是哪个模块
                                String sign = qrCodePaintBookBean.getSign();

                                //标识和参数都不是空才执行内部
                                if (!TextUtils.isEmpty(param) && !TextUtils.isEmpty(sign)) {

                                    //第一种方式： 一个简单的弹窗。
//                                CommUtils.checkDialog(mAlertView);
//                                mAlertView = CommUtils.method_showAlertViewTwoButton(mActivityInstance,//
//                                        StringUtils.getString(R.string.clearcachecancel),//取消
//                                        StringUtils.getString(R.string.clearcachedelete),//删除
//                                        StringUtils.getString(R.string.paitbook_toast_history),//确定供电
//                                        false, new OnItemClickListener() {//
//                                            @Override
//                                            public void onItemClick(Object o, int position) {
//                                                if (position != AlertView.CANCELPOSITION) {
//                                                    //用户确认之后 立即调用接口
//                                                    method_gainData_by_qrCode_for_updateForScanQrCode(param);
//                                                }
//                                                //取消 就取消 不执行任何操作。
//                                            }
//                                        });
//                                mAlertView.show();

                                    //qrCodeResult_decrypt：-->{"param":{"spraySiteId":4},"sign":"SprayReservation"}

                                    //标识是喷涂币支付过来的
                                    if (TextUtils.equals(sign, Parameterkey.SprayReservation)) {

                                        //第二种方式：需要手动输入核销码
                                        method_show_QRCode_has_parse_success_dialog_tips(param);

                                    } else {

                                        //直接展示参数内容？

                                    }


                                } else {
                                    PopTip.show(param).iconWarning();
                                }

                            }

                            //区分一个标识符号：
//                    if (qrCodeResult.startsWith(Parameterkey.QRCODE_PREFIX)) {

                            //如果扫码的内容为空，那么需要提示
                            //这是跳转到-客户关怀的根据二维码获取 优惠券的详情
                        /*if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {
                            method_gainData_by_qrCode_for_rice_ticked(qrCodeResult);
                        } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {
                            method_gainData_by_qrCode_for_customer_care_card(qrCodeResult);
                        } else {
                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "没有执行-调用核销码 获取详情接口");
                        }*/

//                    } else if (qrCodeResult.contains(Parameterkey.QRCODE_HTTP)) {
//                        CommUtils.linkJumpDialog(PaintBookingSumHistoryActivity.this, PaintBookingSumHistoryActivity.this, qrCodeResult);
//                    } else {
//                        CommUtils.textJumpDialog(PaintBookingSumHistoryActivity.this, PaintBookingSumHistoryActivity.this, qrCodeResult);
//                    }

                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }


                } else {

                    if (TextUtils.isEmpty(qrCodeResult_encrypted)) {//服务站运营经理的初始值-1说明没有赋值，提交不过去
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_qrcode_upload), true);
                        mAlertView.show();
                    }

                }

            }

        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);

        if (notDataView != null) {
            notDataView = null;
        }

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (homeMainItemAdapter != null) {
            homeMainItemAdapter.notifyDataSetChanged();
            homeMainItemAdapter = null;
        }

        if (basePopupViewStationType != null) {
            basePopupViewStationType.onDestroy();
            basePopupViewStationType = null;
        }

        CommUtils.checkMaterialDialog(materialDialogDownLoadProgress);
        CommUtils.checkMaterialDialog(materialDialogHasUpdateData);


    }


    //弹窗确认,扫码出加密数据，并且解析成功之后弹窗。
    private void method_show_QRCode_has_parse_success_dialog_tips(String _param) {

        //执行该弹窗的时候要清空弹层以上的所有弹层
        CommUtils.checkMaterialDialog(materialDialogCustomView);
        //引导客户认证的弹窗：
        View viewCard = View.inflate(mActivityInstance, R.layout.paint_booking_popu_input, null);

//        客户未完成认证的弹窗文字提示
//        TextView textViewQRMessage = (TextView) viewCard.findViewById(R.id.tv_name_paintbook_popu_title);
//        textViewQRMessage.setText(message_content);

        //文本输入的内容:核销码
        ClearEditText editViewPaintInput = (ClearEditText) viewCard.findViewById(R.id.editviewpaintinput);

        //确认供电按钮
        RoundTextView textViewToSignatureQRCodeCreateTips = (RoundTextView) viewCard.findViewById(R.id.textviewsurepaintbook);
        //关闭按钮
        RoundTextView textViewSignatureCancelCreateTips = (RoundTextView) viewCard.findViewById(R.id.textviewpaintbookcancel);

        //clicks
        //确认供电按钮
        textViewToSignatureQRCodeCreateTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //获取输入的文本内容
                String inputCode = editViewPaintInput.getText().toString().trim();

                //做拦截，如果输入的是错的，那么提示
                if (TextUtils.isEmpty(inputCode)) {
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.look_into_qrcode_input), true);
                    mAlertView.show();
                    return;
                }

                //先关闭本身的弹窗。
                //关闭软键盘
                KeyboardUtils.hideSoftInput(HomeMainFragmentActivity.this);

                if (materialDialogCustomView != null) {
                    materialDialogCustomView.dismiss();
                }

                //调用喷涂预约供电的接口，上传扫码内容
                method_gainData_by_qrCode_for_updateForScanQrCode(_param, inputCode);


            }
        });

        //关闭
        textViewSignatureCancelCreateTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //此时 弹窗是已经被弹出的
                if (materialDialogCustomView != null) {
                    materialDialogCustomView.dismiss();
                }

            }
        });

        //激发 弹窗弹出内容
        materialDialogCustomView = new MaterialDialog.Builder(HomeMainFragmentActivity.this)
                .customView(viewCard, false)
                .contentColor(ColorUtils.getColor(R.color.buttonnomcolor))//
                //.positiveText("确定")
                .positiveColor(ColorUtils.getColor(R.color.dark))
                //.negativeText("取消")
                .canceledOnTouchOutside(false)
                .show();

    }


    @Override
    protected void methodBack() {
        if (ActivityUtils.isActivityAlive(this)) {
            ActivityUtils.finishActivity(this);
        }
    }

    /**
     * 头像处理
     */
    private void method_avatar(CircleImageView circleImageView, String imageViewPhoto) {

        //LogUtils.d("itchen--MineFragment--imageviewhead是否是空值：" + imageviewhead);

        if (!TextUtils.isEmpty(imageViewPhoto)) {

            Glide.with(HomeMainFragmentActivity.this)//
                    .load(imageViewPhoto)//填充头像信息//
                    .skipMemoryCache(true)//跳过内存缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//不在磁盘中缓存
                    .placeholder(R.drawable.defaulttoub)//
                    .error(R.drawable.defaulttoub)//
                    .fallback(R.drawable.defaulttoub)//
                    .centerCrop()//
                    .transition(withCrossFade())//
                    //.transition(DrawableTransitionOptions.withCrossFade())//动画渐变加载
                    .into(new CustomTarget<Drawable>() {//
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            //手动指定图片内容
                            if (circleImageView != null) {
                                circleImageView.setImageDrawable(resource);//
                            }
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {
                            //
                        }
                    });

            //此刻应该具有点击事件：
            //这个仅仅是测试数据-真实的要关闭。=======================================
            if (circleImageView != null) {

                circleImageView.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        ActivityUtils.startActivity(SettingActivity.class);//设置界面

                        // TODO: 2023-10-17 14:50 临时的跳转到喷涂支付
//                        ActivityUtils.startActivity(PaintBookingMainActivity.class);

                    }
                });

                circleImageView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {

                        if (!DoubleClickListener.isFastDoubleClick()) {

                            if (NetworkUtils.isConnected()) {

                                ArrayList<String> imageList = new ArrayList<>();
                                imageList.add(mSession.getPhotoUrl());

                                //这是预览自定义的内容
                                Album.gallery(HomeMainFragmentActivity.this)
                                        .checkedList(imageList)
                                        //.navigationAlpha(80)
                                        .checkable(false)//是否出现选择对勾内容
                                        .widget(
                                                Widget.newLightBuilder(HomeMainFragmentActivity.this)
                                                        .statusBarColor(Color.WHITE)
                                                        .title(R.string.headerstr)
                                                        .build()
                                        )
                                        .onResult(new Action<ArrayList<String>>() {
                                            @Override
                                            public void onAction(@NonNull ArrayList<String> result) {
                                                //
                                            }

                                        })
                                        .start();
                            }
                        }

                        return true;
                    }
                });
            }

        } else {

            //这里发现头像传递的虽然是空，但是仍然是之前的缓存图片信息

            Glide.with(HomeMainFragmentActivity.this)//
                    .load(R.drawable.defaulttoub)//填充头像信息//
                    .skipMemoryCache(true)//跳过内存缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//不在磁盘中缓存
                    .placeholder(R.drawable.defaulttoub)//
                    .error(R.drawable.defaulttoub)//
                    .fallback(R.drawable.defaulttoub)//
                    .centerCrop()//
                    .transition(withCrossFade())//原始代码
                    //.transition(DrawableTransitionOptions.withCrossFade())//动画渐变加载
                    .into(new CustomTarget<Drawable>() {//
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {

                            //2018年的时候发现此处有报错内容
                            /*Attempt to invoke virtual method
                            'void de.hdodenhof.circleimageview.CircleImageView.setOnClickListener(android.view.View$OnClickListener)'
                            on a null object reference*/
                            //手动指定图片内容..
                            if (circleImageView != null) {
                                circleImageView.setImageDrawable(resource);//
                            }

                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {
                            //
                        }
                    });

            //此刻应该不具备点击事件
            if (circleImageView != null) {
                circleImageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //有没又图片信息，都有点击能力
                        //LogUtils.d("itchen--点击消耗");
                        ActivityUtils.startActivity(SettingActivity.class);//设置界面
                    }
                });
            }

        }
    }


    //根据扫描的二维码信息，传递给后台 开启电源 开始喷涂，执行这条预约数据。
    private void method_gainData_by_qrCode_for_updateForScanQrCode(String _rqCode_content_param, String _accessCode) {

//      LogUtils.d(ConstantSign.LOGCAT_NOMAL + "调用 餐券发放-餐券核销接口--method_gainData_by_qrCode_for_rice_ticked");

        HashMap<String, Object> map = new HashMap<>();
//        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
//        map.put(Parameterkey.reservationSiteId, paintBookingItemBean_shareInfo.getReservationSiteId());//预约单明细ID
//        map.put(Parameterkey.spraySiteId, _rqCode_content);//扫码可获取场地ID
        //{"spraySiteId":4}


        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATEFORSCANQRCODE);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateForScanQrCode_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        String stringBuffertoString = CommUtils.splitFrontAndBehindAddOneParam(_rqCode_content_param, Parameterkey.accessCode, _accessCode);
        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "stringBuffer-->" + stringBuffertoString);

        //原始代码
//        String jsonObject = JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateForScanQrCode(RequestBody.create(stringBuffertoString, MediaType.parse(ApiService.HEADER_JSON)))
                .compose(HomeMainFragmentActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //隐藏软键盘
                        if (KeyboardUtils.isSoftInputVisible(HomeMainFragmentActivity.this)) {
                            KeyboardUtils.hideSoftInput(HomeMainFragmentActivity.this);
                        }

                        CommUtils.checkMaterialDialog(materialDialog);

                        if (materialDialogCustomView != null) {
                            materialDialogCustomView.dismiss();
                        }

                        //这里要给一个醒目提示？

                        if (!TextUtils.isEmpty(serverMessage)) {
//                            PopTip.show(serverMessage).iconWarning();
                            CommUtils.checkDialog(mAlertView);
                            mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, serverMessage, true);
                            mAlertView.show();

                        } else {
                            PopTip.show(getString(R.string.action_abnormal)).iconWarning();
                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        //隐藏软键盘
                        if (KeyboardUtils.isSoftInputVisible(HomeMainFragmentActivity.this)) {
                            KeyboardUtils.hideSoftInput(HomeMainFragmentActivity.this);
                        }

                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);

                    }
                }).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String string) throws Throwable {

                        if (materialDialogCustomView != null) {
                            materialDialogCustomView.dismiss();
                        }

                        //隐藏软键盘
                        if (KeyboardUtils.isSoftInputVisible(HomeMainFragmentActivity.this)) {
                            KeyboardUtils.hideSoftInput(HomeMainFragmentActivity.this);
                        }

                        CommUtils.checkMaterialDialog(materialDialog);

                        // TODO: 2023-12-12 14:37 传递完毕之后，执行什么？直接提示提交成功？
//                        if (couponCustomer != null) {
//                            method_show_dist_dialog(_rqCode_content, couponCustomer);
//                        } else {
//                            ToastUtils.showShort(getString(R.string.action_abnormal));
//                        }

                        methodSubmitSuccess(HomeMainFragmentActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {
                                //是要重新刷新列表，变更状态的

                                gainDatas();
                                //弹出一个确认弹出，确认送电 开始喷涂预约的能力。


                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        CommUtils.checkMaterialDialog(materialDialog);

                        if (apiException != null) {
                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "执行的报错内容是-->" + apiException.getDisplayMessage());
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }
                        }

                    }
                });


    }

    //跳转到扫一扫页面
    private void methodToQRCode() {

        //添加扫一扫，2023-12-13 17:19:40 目前是扫码打开喷涂房的逻辑
        Bundle bundle = new Bundle();
        bundle.putInt(ExtraKey.EXTRA_QRCODE_INFO, 0);
        bundle.putInt(ExtraKey.BGAQRCODE_KEY, ExtraValue.BGAQRCODE_VALUE_FROM_HOME_MAIN);
        ActivityUtils.startActivity(bundle, MyBGAQRCodeActivity.class);

    }

    @Override
    public void dialogDimss(MaterialDialog _materialDialog) {

        CommUtils.checkMaterialDialog(_materialDialog);

    }
}